package com.shakespace.artofandroid.chapter08window

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.MotionEvent
import android.view.WindowManager
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.shakespace.artofandroid.R
import com.shakespace.firstlinecode.global.showToast
import kotlinx.android.synthetic.main.activity_window.*

class  WindowActivity : AppCompatActivity() {

    var layoutParams: WindowManager.LayoutParams? = null
    lateinit var floatButton: Button

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_window)

        floatButton = Button(this)

        tv_create_window.setOnClickListener {
            /**
             * Manifest 有几个不同的类
             */
//            if ((ContextCompat.checkSelfPermission(
//                    this,
//                    Manifest.permission.SYSTEM_ALERT_WINDOW
//                )) == PackageManager.PERMISSION_GRANTED
//            ) {
//                // add window
//                addViewToWindow()
//            } else {
//                // SYSTEM_ALERT_WINDOW 权限无法用代码申请
//                ActivityCompat.requestPermissions(
//                    this,
//                    arrayOf(Manifest.permission.SYSTEM_ALERT_WINDOW),
//                    1
//                )
//            }

            if (!Settings.canDrawOverlays(this)) {
                getOverlayPermission()
            } else {
                addViewToWindow()
            }

        }

        var rawX = 0
        var rawY = 0
        floatButton.setOnTouchListener { v, event ->
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
                    rawX = event.getRawX().toInt()
                    rawY = event.getRawY().toInt()
                    false
                }
                MotionEvent.ACTION_MOVE -> {
                    layoutParams?.apply {
                        x = x + event.getRawX().toInt() - rawX
                        y = y + event.getRawY().toInt() - rawY
                        windowManager.updateViewLayout(v, this)
                        rawX = event.getRawX().toInt()
                        rawY = event.getRawY().toInt()
                    }
                    true
                }
                else -> {
                    false
                }
            }
        }


//        tv_create_many.setOnClickListener {
//            repeat(101) {
//                tv_create_many
//                    .postDelayed({
//                        start(TestActivity::class.java)
//                    },300)
//            }
//        }

    }

    @TargetApi(Build.VERSION_CODES.M)
    private fun getOverlayPermission() {
        val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
        intent.data = Uri.parse("package:$packageName")
        startActivityForResult(intent, 0)
    }

    private fun addViewToWindow() {
        floatButton.text = "FloatButton"
        layoutParams = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                // WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,  已废弃
                //                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                //                    WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW,
                WindowManager.LayoutParams.LAST_APPLICATION_WINDOW,
                0,
                PixelFormat.TRANSPARENT
            )
        } else {
            WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                0,
                PixelFormat.TRANSPARENT
            )
        }.apply {
            flags = ( // 换行需要带括号。。。
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                        or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED // 废弃
                    )

            gravity = Gravity.LEFT or Gravity.TOP
            x = 100
            y = 200
        }
        windowManager.addView(floatButton, layoutParams)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        val rawX = event?.rawX
        val rawY = event?.rawY
        when (event?.action) {
            MotionEvent.ACTION_MOVE -> {
                layoutParams?.apply {
                    x = rawX?.toInt() ?: this.x
                    y = rawY?.toInt() ?: this.y
                    windowManager.updateViewLayout(floatButton, this)
                    return true
                }

            }
            else -> {
                return super.onTouchEvent(event)
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // add window
                    addViewToWindow()
                } else {
                    showToast("do not have permission")
                }
            }
            else -> " "
        }
    }
}
